import axios from '@/axios';
import { defineComponent, reactive, ref, watch } from 'vue'
import MyMarkDown from '../MyMarkDown';
import {isEmpty, dateFormat, parseJson} from "@/utils/common"
import classes from './index.module.scss';
import * as _ from 'lodash'
import { ElMessage } from 'element-plus';
import { Briefcase, CaretBottom, CaretTop, ChatDotSquare, HomeFilled, UserFilled, View } from '@element-plus/icons-vue';

export default defineComponent({
    name: 'MyDocument',
    props: {
        modelValue: {
            type: String
        },
        tree: {
            type: Object,
            default: {
                rowField: "id",
                parentField: "sjbj",
                hasChild: "myhaschild",
                label: 'bt',
            }
        },
        searchParams: {
            type: Object,
            default: {
                sjdx: {
                    dxdm: "SYS_SJGL_GRBJ"
                },
                sys: {
                    cllx: "select"
                },
                yobj: {
                    yxx: "1",
                    ckwd: "1",
                },
                page: {
                    pageSize: "50000"
                }
            }
        },
        commentQuery: {
            type: Object,
            default: {
                page: {
                    pageNumber: 1,
                    pageSize: 10
                },
                sjdx: {
                    dxdm: "SYS_WDGL_PL"
                },
                sys: {
                    cllx: "select"
                },
                yobj: {
                    xgpl: "my-null",
                    czlb: "01",
                    yxx: "1",
                    xgwd: "42F03A5FE3B9425E98E46B52298485A2"
                }
            }
        },
        customStyle: {
            type: String,
            default: ""
        }
    },
    setup(props, ctx) {
        const searchKey = ref("")
        const currentDoc = ref()
        const treeRef = ref()
        const treeLazy = ref(true)
        const treeList = ref([] as any[])
        const loadTreeList = ref([] as any[])
        const commentList = ref([] as any[])
        const homeDoc = ref({
            bt: "数据世界"
        })
        const treeVisible = ref(false)
        const foldVisible = ref(false)
        const defaultProps: any = {
            label: props.tree.label,
            isLeaf: 'leaf',
        }
        const page = reactive({
            pageNumber: 1,
            pageSize: 10,
            totalRow: 0
        })
        const commentValue = ref("")
        const subCommentValue = ref("")
        const getCommentList = () => {
            let query = JSON.parse(JSON.stringify(props.commentQuery))
            query.page.pageNumber = page.pageNumber
            query.page.pageSize = page.pageSize

            query.yobj.xgwd = currentDoc.value.id
            axios.post(query).then(res => {
                if (res.status) {
                    res.data.list.map((item: any) => {
                        item.replyShow = false;
                        item.replyList = [];
                        item.replyValue = ""
                        item.replyPage = {
                            pageNumber: 1,
                            pageSize: 10,
                            totalRow: 0
                        }
                    })
                    commentList.value = res.data.list
                    page.totalRow = res.data.totalRow
                }
            })
        }
        const getReplyList = (item: any) => {
            let query = JSON.parse(JSON.stringify(props.commentQuery))
            query.yobj.xgpl = item.id
            query.yobj.xgwd = undefined
            query.page.pageNumber = item.replyPage.pageNumber
            query.page.pageSize = item.replyPage.pageSize
            axios.post(query).then(res => {
                if (res.status) {
                    item.replyList = res.data.list
                    item.replyPage.totalRow = res.data.totalRow
                }
            })
        }

        const handleNodeClick = (data: any) => {
            let currentQuery = JSON.parse(JSON.stringify(props.searchParams))
            currentQuery.yobj.id = data.id
            currentQuery.yobj.wdxq = "1"
            axios.post(currentQuery, { tloading: false }).then(res => {
                if (res.status && res.data.list && res.data.list.length > 0) {
                    currentDoc.value = res.data.list[0]
                    if(currentDoc.value.nr){
                        currentDoc.value.nr = currentDoc.value.nr.replace(/\(##urlRoot##/g, `(${axios.getBaseURL()}/`);
                        currentDoc.value.nr = currentDoc.value.nr.replace(/"##urlRoot##/g, `"${axios.getBaseURL()}/`);
                    }
                    currentDoc.value.kzxxObj = parseJson(res.data.list[0].kzxx);
                    getCommentList()
                }
            })
        }
        const loadNode = async (node: any, resolve: (data: any) => void) => {
            let query = JSON.parse(JSON.stringify(props.searchParams))

            query.yobj[props.tree.parentField] = node.data[props.tree.rowField]

            if (node.level === 0 && !isEmpty(props.modelValue)) {
                query.yobj[props.tree.parentField] = props.modelValue
                let currentQuery = JSON.parse(JSON.stringify(query))
                currentQuery.yobj.id = props.modelValue
                currentQuery.yobj.wdxq = "1"
                await axios.post(currentQuery, { tloading: false }).then(res => {
                    if (res.status && res.data.list && res.data.list.length > 0) {
                        res.data.list[0].kzxxObj = parseJson(res.data.list[0].kzxx);
                        currentDoc.value = res.data.list[0]
                        if(currentDoc.value.nr){
                            currentDoc.value.nr = currentDoc.value.nr.replace(/\(##urlRoot##/g, `(${axios.getBaseURL()}/`);
                            currentDoc.value.nr = currentDoc.value.nr.replace(/"##urlRoot##/g, `"${axios.getBaseURL()}/`);
                        }
                        homeDoc.value = currentDoc.value
                        treeVisible.value = res.data.list[0][props.tree.hasChild]
                        foldVisible.value = res.data.list[0][props.tree.hasChild]
                        if (res.data.list[0].pl === "1") {
                            getCommentList()
                        }
                    } else {
                        treeVisible.value = true
                    }
                })
            } else {
                treeVisible.value = true
            }
            if (foldVisible.value) {
                axios.post(query, { tloading: false }).then((res) => {
                    if (res.status) {
                        res.data.list.map((item: any) => {
                            item.leaf = item.parent <= 0
                        })
                        if (node.level === 0) {
                            loadTreeList.value = res.data.list
                        }
                        return resolve(res.data.list)
                    }
                })
            }
        }

        const goHome = () => {
            currentDoc.value = homeDoc.value
        }

        const debounceSearch = _.debounce((val: any) => search(val), 700);

        const search = (val: any) => {
            if (val.length > 0) {
                let query = JSON.parse(JSON.stringify(props.searchParams))
                query.yobj.sfsxjg = '0'
                query.yobj[props.tree.parentField] = props.modelValue
                query.sys.searchKey = val
                axios.post(query, { tloading: false }).then((res) => {
                    if (res.status && res.data.list) {
                        res.data.list.map((item: any) => {
                            item.leaf = item.parent <= 0
                        })
                        if (searchKey.value.length > 0) {
                            treeList.value = res.data.list
                        }
                    }
                })
            } else {
                treeList.value = loadTreeList.value
            }
        }
        const updatePl = (val: any) => {
            commentValue.value = val
        }
        const submit = () => {
            if (!isEmpty(commentValue.value)) {
                console.log(commentValue.value)
                let query = JSON.parse(JSON.stringify(props.commentQuery))
                query.sys.cllx = "insert"
                query.yobj.czlb = "01"
                query.yobj.xgpl = undefined
                query.yobj.nr = commentValue.value
                query.yobj.xgwd = currentDoc.value.id
                axios.post(query).then(res => {
                    if (res.status) {
                        ElMessage.success("发布成功");
                        commentValue.value = ""
                        getCommentList()
                    }
                })
            }
            else {
                ElMessage.warning("请先输入评论");
            }
        }
        const replySubmit = (item: any) => {
            if (!isEmpty(item.replyValue)) {
                let query = JSON.parse(JSON.stringify(props.commentQuery))
                query.sys.cllx = "insert"
                query.yobj.czlb = "01"
                query.yobj.nr = item.replyValue
                query.yobj.xgwd = currentDoc.value.id
                query.yobj.xgpl = item.id
                axios.post(query).then((res: any) => {
                    if (res.status) {
                        ElMessage.success("发布成功");
                        item.replyValue = ""
                        getReplyList(item)
                    }
                })

            } else {
                ElMessage.warning("请先输入评论");
            }
        }
        const handleSizeChange = (val: number) => {
            page.pageSize = val
            getCommentList()
        }
        const handleCurrentChange = (val: number) => {
            page.pageNumber = val
            getCommentList()
        }
        const handleReplySizeChange = (val: number, item: any) => {
            item.replyPage.pageSize = val
            getReplyList(item)
        }
        const handleReplyCurrentChange = (val: number, item: any) => {
            item.replyPage.pageNumber = val
            getReplyList(item)
        }


        const replyShow = (item: any) => {
            item.replyShow = !item.replyShow
            if (item.replyShow && item.plSl > 0) {
                getReplyList(item)
            }
        }

        const commentCz = (cz: string, id?: string) => {
            let query = JSON.parse(JSON.stringify(props.commentQuery))
            let czlb = "02"
            if (cz === 'cai') {
                czlb = "03"
            }
            if (id) {
                query.yobj = {
                    id: id,
                    yxx: "0"
                }
                query.sys.cllx = "update"
            } else {
                query.yobj = {
                    czlb: czlb,
                    xgwd: currentDoc.value.id,
                }
                query.sys.cllx = "insert"
            }


            axios.post(query).then(res => {
                if (res.status) {
                    if (id) {
                        currentDoc.value[cz + "Dqyh"] = undefined
                        currentDoc.value[cz + "Sl"]--
                    } else {
                        currentDoc.value[cz + "Dqyh"] = res.data.id
                        currentDoc.value[cz + "Sl"]++
                    }
                }
            })
        }

        const replyCz = (cz: string, item: any) => {
            let query = JSON.parse(JSON.stringify(props.commentQuery))
            let czlb = "02"
            if (cz === 'cai') {
                czlb = "03"
            }
            if (item[cz + "Dqyh"]) {
                query.yobj = {
                    id: item[cz + "Dqyh"],
                    yxx: "0"
                }
                query.sys.cllx = "update"
            } else {
                query.yobj = {
                    czlb: czlb,
                    xgpl: item.id,
                    xgwd: currentDoc.value.id,
                }
                query.sys.cllx = "insert"
            }
            axios.post(query).then(res => {
                if (res.status) {
                    if (item[cz + "Dqyh"]) {
                        item[cz + "Dqyh"] = undefined
                        item[cz + "Sl"]--
                    } else {
                        item[cz + "Dqyh"] = res.data.id
                        item[cz + "Sl"]++
                    }
                }
            })
        }

        const replyPer = (item: any, item1: any) => {
            item.replyValue = "回复 " + item1.cjrxm + "："
            console.log(item)
        }

        watch(() => searchKey.value, (val) => {
            debounceSearch(val)
        })


        return {
            replySubmit,
            commentCz,
            replyCz,
            replyShow,
            replyPer,
            handleCurrentChange,
            handleSizeChange,
            handleReplyCurrentChange,
            handleReplySizeChange,
            page,
            submit,
            commentValue,
            subCommentValue,
            updatePl,
            treeList,
            searchKey,
            goHome,
            treeRef,
            treeLazy,
            // filterNode,
            foldVisible,
            treeVisible,
            commentList,
            currentDoc,
            homeDoc,
            defaultProps,
            handleNodeClick,
            loadNode
        }
    },
    render() {
        return (
            <div class={classes.container} style={this.customStyle}>
                <div class={classes.tree} v-show={this.treeVisible}>
                    <el-link style="padding:10px" underline={false} onClick={this.goHome} icon={HomeFilled}> {this.homeDoc.bt}</el-link>
                    <el-input v-model={this.searchKey} size="small" clearable placeholder="输入关键字"></el-input>
                    <el-tree
                        data={this.treeList}
                        ref="treeRef"
                        node-key={this.tree.rowField} load={this.loadNode} lazy={this.treeLazy} highlight-current
                        props={this.defaultProps}
                        onNode-click={this.handleNodeClick}
                    ></el-tree>
                </div>

                {!isEmpty(this.currentDoc) ? <div style="position:relative;width:100%;padding:0 50px;">
                        {this.foldVisible ? <div style="position:absolute; left:5px; top:5px;">
                            <el-link onClick={() => { this.treeVisible = !this.treeVisible }} style="font-size:20px;z-index:99" underline={false} icon={this.treeVisible ? "el-icon-s-fold" : "el-icon-s-unfold"} >
                            </el-link>
                        </div> : null}
                        <el-scrollbar style="width:100%;" key={this.currentDoc.id}><div class={classes.content}>
                            <div v-show={this.currentDoc.kzxxObj.titleShow!==false} class={classes.title}>{this.currentDoc.bt}</div>
                            {this.currentDoc.nr && !isEmpty(this.currentDoc.nr) ? (this.currentDoc.nr.substr(0, 1) === '<' && this.currentDoc.nr.substr(-1) === '>' ? <div class={classes.html} v-html={this.currentDoc.nr}></div> : <div class={classes.MyMarkDown}><MyMarkDown modelValue={this.currentDoc.nr} mode="preview"></MyMarkDown></div>) : null}
                            <div>
                                {this.currentDoc.zan === "1" ? <el-button type={this.currentDoc.zanDqyh ? "primary" : "default"} icon={CaretTop} onClick={() => this.commentCz('zan', this.currentDoc.zanDqyh)}>赞同 {this.currentDoc.zanSl}</el-button> : null}
                                {this.currentDoc.cai === "1" ? <el-button type={this.currentDoc.caiDqyh ? "primary" : "default"} icon={CaretBottom} onClick={() => this.commentCz('cai', this.currentDoc.caiDqyh)}></el-button> : null}
                            </div>
                            <div class={classes.info}>
                                编辑于 {dateFormat(this.currentDoc.gxsj, 'YYYY-MM-DD HH:mm:ss')}
                                <div><el-icon><Briefcase /></el-icon>{this.currentDoc.cjrdwmc} <el-icon style="margin-left:8px"><UserFilled /></el-icon> {this.currentDoc.cjrxm}<el-icon style="margin-left:8px" ><View /></el-icon> {this.currentDoc.ydcs}</div>
                            </div>
                            {this.currentDoc.pl === "1" ? <div style="margin:10px;border-top:1px solid #e4e7ed">
                                {this.commentList.map(item => {
                                    return <div style="padding:10px;">
                                        <div style="display:flex;align-items:center">
                                            <el-avatar size={28} icon={UserFilled} src={"data:image/jpg;base64," + item.yhtx} />
                                            <div style="padding-left:4px;font-size:16px;flex:1">{item.cjrxm}</div>
                                        </div>
                                        <MyMarkDown modelValue={item.nr} mode="preview"></MyMarkDown>
                                        {/* <div style="padding:4px 28px;font-size:14px">{item.nr}</div> */}
                                        <div style="padding:4px 28px;font-size:12px; color:#A8ABB2;display:flex;align-items:center">
                                            <div>{dateFormat(item.gxsj, 'YYYY-MM-DD HH:mm:ss')}</div>
                                            {this.currentDoc.pl === "1" ? <el-link style="margin-left:8px" type="info" icon={ChatDotSquare} onClick={() => { this.replyShow(item) }}><span style="font-size:12px;">评论({item.plSl})</span> </el-link>
                                                : null}
                                            {this.currentDoc.zan === "1" ?
                                                <el-link style="margin-left:8px" type={item.zanDqyh ? "primary" : "info"} icon={CaretTop} onClick={() => this.replyCz('zan', item)} ><span style="font-size:12px;">赞同({item.zanSl})</span></el-link> : null}
                                        </div>
                                        <div v-show={item.replyShow}>
                                            {item.replyList.map((item1: any) => {
                                                return <div style="margin:0 20px;padding:10px; background-color:#F2F6FC"><div style="display:flex;align-items:center">
                                                    <el-avatar size={28} icon={UserFilled} src={"data:image/jpg;base64," + item1.yhtx} />
                                                    <div style="padding-left:4px;font-size:16px;flex:1">{item1.cjrxm}</div>
                                                </div>
                                                    <div style="padding:4px 28px;font-size:14px">{item1.nr}</div>
                                                    <div style="padding:4px 28px;font-size:12px; color:#A8ABB2;display:flex;align-items:center">
                                                        <div>{dateFormat(item1.gxsj, 'YYYY-MM-DD HH:mm:ss')}</div>
                                                        <el-link style="margin-left:8px" type="info" icon={ChatDotSquare} onClick={() => this.replyPer(item, item1)}><span style="font-size:12px;">回复</span> </el-link>
                                                        {this.currentDoc.zan === "1" ? <el-link style="margin-left:8px" type={item1.dqyhZan ? "primary" : "info"} icon={CaretTop} onClick={() => this.replyCz('zan', item1)}><span style="font-size:12px;">赞同({item1.zanSl})</span></el-link> : null}
                                                    </div></div>
                                            })}
                                            {item.replyList.length > 0 ? <el-pagination
                                                style="margin:10px 30px;text-align: right"
                                                v-model:current-page={item.replyPage.pageNumber}
                                                v-model:page-size={item.replyPage.pageSize}
                                                page-sizes={[10, 20, 50, 100, 500]}
                                                small
                                                layout="total, prev, pager, next"
                                                total={item.replyPage.totalRow}
                                                onSize-change={(val: number) => this.handleReplySizeChange(val, item)}
                                                onCurrent-change={(val: number) => this.handleReplyCurrentChange(val, item)}
                                            /> : <div style="font-size:14px;line-height:40px;text-align:center;color:#A8ABB2">暂无评论</div>}
                                            <div style="display:flex;padding:0 10px;align-items:flex-end">
                                                <el-input
                                                    type="textarea"
                                                    autosize={{ minRows: 4 }}
                                                    placeholder="请输入内容"
                                                    v-model={item.replyValue}
                                                >
                                                </el-input>
                                                <el-button size="small" link type='primary' style="margin-left:10px;" onClick={() => this.replySubmit(item)}>发布</el-button>
                                            </div>
                                        </div>
                                    </div>
                                })}
                                {this.commentList.length > 0 ? <el-pagination
                                    style="float:right;margin-bottom:10px;"
                                    v-model:current-page={this.page.pageNumber}
                                    v-model:page-size={this.page.pageSize}
                                    page-sizes={[10, 20, 50, 100, 500]}
                                    layout="total, sizes, prev, pager, next, jumper"
                                    total={this.page.totalRow}
                                    onSize-change={this.handleSizeChange}
                                    onCurrent-change={this.handleCurrentChange}
                                /> : <div style="font-size:14px;line-height:40px;text-align:center;color:#A8ABB2">
                                    暂无评论
                                </div>}
                                <MyMarkDown {...{ height: "200px" }} modelValue={this.commentValue} onUpdate:modelValue={this.updatePl}></MyMarkDown>
                                <el-button size="small" type="primary" style="margin-top:10px;float:right" onClick={this.submit}>发布评论</el-button>
                                <div style="height:50px"></div>
                            </div> : null}
                        </div>
                        </el-scrollbar></div>
                    : null}

            </div>
        )
    }
})
